package com.bruce.tool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.bruce.service.UserService;

/**
 * 
 * @Description: 配置1
 * @author JW
 * @date:   2019年3月12日 上午9:08:14
 */
public class MyInterceptor1 implements HandlerInterceptor{
	public static Logger log = LoggerFactory.getLogger(HandlerInterceptor.class);
	@Autowired
	private UserService userService;	


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURI();
		Object userid = request.getSession().getAttribute("LoginUserId");
		log.info("url: "+url+" & codeid: "+  request.getSession().getId()+" & LoginUserId: "+userid);
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		response.addHeader("Access-Control-Allow-Headers",
				"Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token");

		//				return true;//for test
		//释放系统异常
		if ("/error".equals(url)){
			return  true;
		}

		//静态资源
		if(url.substring(0, 16).equals("/view/ManagePage")) {
			//公共资源

			//后台登入页面资源
			if("/static".equals(url.substring(16,23)) ){
				return true;
			}
			if("/lib".equals(url.substring(16,20)) ){
				return true;
			}
			if("/view/ManagePage/404.html".equals(url) ) {
				return true;
			}
			if("/view/ManagePage/login.html".equals(url) ) {
				return true;
			}
			if("/view/ManagePage/loginDef.html".equals(url) ) {
				return true;
			}
			
			//前台登入页面资源
		}

		//后台登入权限拦截
		if(url.substring(0, 8).equals("/manager")) {
			//公开页面请求放弃拦截
			if(url.equals("/manager/user/userLoginDef")
					|| url.equals("/manager/user/userLogin")
					|| url.equals("/manager/user/userQuit")
					|| url.equals("/manager/user/defaultKaptcha")
					) {
				return true;
			}
			
		}
		//权限验证
		if(null != userid && !JWBean.isEmpty(userid.toString())) {
			boolean  flag = userService.isPermission(Integer.valueOf(String.valueOf(userid)), url);
			log.info("权限: "+flag);
			return flag;
		}
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		//	        System.out.println("请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//		System.out.println("在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
	}

}
